const db = require('./src/config/database');

// 确保所有需要的货位都存在于货位表中
function ensureAllLocationsExist() {
    // 从insertRealData.js中提取的货位列表
    const requiredLocations = [
        'WH01-A-01-01-01',
        'WH01-A-01-01-02',
        'WH01-A-01-01-03',
        'WH01-A-01-01-04',
        'WH01-B-02-02-01',
        'WH01-B-02-02-02',
        'WH01-C-03-03-01',
        'WH01-C-03-03-02',
        'WH01-D-01-01-01',
        'WH01-D-01-01-02',
        'WH01-D-01-01-03'
    ];

    let completed = 0;
    const total = requiredLocations.length;

    requiredLocations.forEach(locationCode => {
        // 解析货位编码
        const parts = locationCode.split('-');
        const warehouse = parts[0];
        const aisle = parts[1];
        const row = parts[2];
        const column = parts[3];
        const level = parts[4];

        // 检查货位是否已存在
        db.get("SELECT id FROM locations WHERE location_code = ?", [locationCode], (err, row) => {
            if (err) {
                console.error('检查货位失败:', err.message);
                checkComplete();
                return;
            }

            if (!row) {
                // 货位不存在，插入新货位
                const sql = `INSERT OR IGNORE INTO locations (location_code, aisle, row, column, level, status) VALUES (?, ?, ?, ?, ?, ?)`;
                db.run(sql, [locationCode, aisle, row, column, level, 'enabled'], (err) => {
                    if (err) {
                        console.error('插入货位失败:', err.message);
                    } else {
                        console.log(`货位已插入: ${locationCode}`);
                    }
                    checkComplete();
                });
            } else {
                console.log(`货位已存在: ${locationCode}`);
                checkComplete();
            }
        });
    });

    function checkComplete() {
        completed++;
        if (completed === total) {
            console.log('所有货位检查完成。');
            // 延迟关闭数据库连接以确保所有操作完成
            setTimeout(() => {
                db.close();
            }, 1000);
        }
    }
}

// 执行货位检查
console.log('开始确保所有货位都存在...');
ensureAllLocationsExist();